<?php

namespace App\Business\Users;

use App\Business\BusBase;
use App\Business\DataLog\DataLogin;
use App\Business\ReturnResult;
use App\Extend\Regex;
use App\Extend\UserIDInfo;
use App\Jobs\LogQueue;
use App\User;
use App\Models\users;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

/**
 * Class Login 登录
 * @package App\Business\Users
 */
class Register extends Login
{
    use UserIDInfo;
    protected function Handle()
    {
        $userName=strtolower($this->userName);

        $password=Hash::make($this->password);


        if($this->CheckUserIsExist())
        {
            return ReturnResult::Error(null, "用户名已被注册");
        }



        //注册用户

        $user=new User();
        $user->userName=$userName;
        $user->password=$password;

        $user->save();

        $id=$user->ID;

        if($id!==null)
        {

            Auth::login($user);
            $this->setUserID($id);

            //登录成功，记录到登录日志
            dispatch( new LogQueue(new DataLogin()));

            return ReturnResult::Success(request()->session()->token());
        }else
        {
            return ReturnResult::Error(null,"注册失败");
        }

    }


    public function GetBusinessName()
    {
        return "用户名密码注册";
    }


    /**
     * 检测用户是否存在
     * @return bool
     */
    protected function CheckUserIsExist()
    {

        $user= users::where("userName","=",$this->userName)->first();

        if($user) return true;

        return false;

    }


}